//
//  AppDelegate.swift
//  sinaWeibo
//
//  Created by 张国梁 on 16/3/26.
//  Copyright © 2016年 CoderGL. All rights reserved.
//

import UIKit
import SDWebImage

let SwitchRootViewControllerKey = "switchRootViewControllerKey"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.switchRootViewController(_:)), name: SwitchRootViewControllerKey, object: nil)
        
        
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = rootViewController()
        window?.makeKeyAndVisible()
        return true
    }
    
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func rootViewController() -> UIViewController {
        if UserAccount.isOAuth() {
            return isNewupdate() ? NewfeatureViewController() : MainTabBarViewController()
        } else {
            return MainTabBarViewController()
        }
    }
    
    func switchRootViewController(notification : NSNotification) -> Void {
        if notification.object as! Bool {
            window?.rootViewController = MainTabBarViewController()
        } else {
            window?.rootViewController = WelcomeViewController()
        }
    }
    
    // 判断是否是新版本
    private func isNewupdate() -> Bool {
        // 取出当前版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        // 取出sandbox中的版本
    let sandBoxVersion = NSUserDefaults.standardUserDefaults().objectForKey("CFBundleShortVersionString") as? String ?? ""
        
        // 对比版本号(如果当前版本号大于沙盒中的版本号)那就返回true否则返回false
        if currentVersion.compare(sandBoxVersion) == NSComparisonResult.OrderedDescending {
            NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "CFBundleShortVersionString")
            return true
        } else {
            return false
        }
    }
    
    
    func applicationDidReceiveMemoryWarning(application: UIApplication) {
        SDImageCache.sharedImageCache().clearMemory()
        SDWebImageManager.sharedManager().cancelAll()
    }
}

